class Detail {
    constructor() {
        //显示名字
        this.getData()
        //显示购物车数量
        this.shopNum()
        this.bindEve()
    }
    //绑定事件
    bindEve = () => {
        //给每个li绑定点击事件
        this.$('.detail_tab_list ul li').forEach((li, index) => {
            li.addEventListener('click', this.liClick.bind(this, index))
        });
        //给小图片绑定移入事件
        this.$('.preview_img').addEventListener('mouseenter', this.enterIn)
        this.$('.preview_img').addEventListener('mouseleave', this.enterOut)
        this.$('.preview_img').addEventListener('mousemove', this.moveOut)
        //小图片下的 小图片
        this.$('.list_item li').forEach((li, index) => {
            // console.log(li, index);
            li.addEventListener('click', this.changePhoto.bind(this, index))
        });
        //上一个图片  下一个图片
        this.$('.arrow_prev').addEventListener('click', this.preImg)

        this.$('.arrow_next').addEventListener('click', this.nextImg)
        //点击关闭广告
        this.$('.close-btn').addEventListener('click', this.closeAd)
        //给发表评论按钮点击绑定事件
        this.$('#btn').addEventListener('click', this.discuss)
        //点击事件  加入购物车
        this.$('.addCar').addEventListener('click', this.addCart)
        //分发事件
        this.$('.choose_amount').addEventListener('click', this.dispach)
        //输入框失去焦点事件
        this.$('.choose_amount input').addEventListener('blur', this.inputNum)

    }
    //分发事件  区分当前操作
    dispach = (eve) => {
        let tar = eve.target
        //判断点击的 加 减
        if (tar.classList.contains("add") || tar.classList.contains("reduce")) {
            this.cartNum(tar)
        }

    }

    //最终购物车的数量
    // num = 1
    cartNum = (tar) => {
        let num = this.$('.choose_amount input').value
        // console.log(num);
        //添加数量
        if (tar.classList.contains("add")) {
            num++
            if (num < 1) num = 1
            this.$('.choose_amount input').value = num
        }
        if (tar.classList.contains("reduce")) {
            num--
            if (num < 1) num = 1
            this.$('.choose_amount input').value = num
        }
    }
    //输入框数量
    inputNum = () => {
        let num = this.$('.choose_amount input').value - 0
        //正则判断输入的是不是数字
        let reg = /^[0-9]*[1-9][0-9]*$/

        if (!reg.test(num)) {
            layer.msg('当前输入内容错了');
            this.$('.choose_amount input').value = ""
            return
        }
    }
    //加入购物车
    addCart = () => {
        let token = localStorage.getItem("token")
        // console.log(token);

        //给服务器发请求  设置编码
        axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        if (!token) location.href = './login.html?returnUrl=./detail.html';
        let id = localStorage.getItem("user_id")
        let goodsId = localStorage.getItem("goodsId") - 0

        let num = this.$('.choose_amount input').value



        let parm = `id=${id}&goodsId=${goodsId}`
        axios.post(`http://localhost:8888/cart/add`, parm)
            .then(res => {
                let { data: { code } } = res

                if (code == 1) {
                    layer.msg('加入购物车成功');
                } else {
                    location.href = './login.html?returnUrl=./detail.html';
                }
            })

    }


    //发表评论
    discuss = () => {
        //先获取输入框的值  不能为空
        if (this.$('#text')[1].value.trim() == "") {
            layer.msg('亲,评论内容不能为空哦');
            return
        }
        // 创建li标签
        let li = document.createElement("li")
        li.innerHTML = ` <a href="#"></a>
       <div class="comment-main-r">
           <div class="main-top">
               b***1 (匿名) 评论于 2012年11月02日 17:46
           </div>
           <div class="main-bd">
               ${this.$('#text')[1].value}<br>
               颜色分类：金 8G+218G
           </div>
       </div>
       `//——这行代码为插入，将当前的li标签，插在ul的第一个子标签之前，即新的li标签每次都插入在最前面。
        this.$('.comment-main').insertBefore(li, this.$('.comment-main').children[0])
        this.$('#text')[1].value = ""
    }
    //关闭广告
    closeAd = () => {
        this.$('.mobile img').style.display = "none"
        this.$('.close-btn').style.display = "none"
    }
    //发送请求 获取数据 修改名字
    async getData() {
        // console.log(this);
        axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        axios.defaults.headers.common['Authorization'] = localStorage.getItem("token")
        let res = await axios.get("http://localhost:8888/users/info?id=" + localStorage.getItem("user_id"))

        let { data, status } = res
        // console.log(data.info.nickname, this);
        if (status == 200 && data.code == 1) {
            this.$('.nav').firstElementChild.firstElementChild.innerHTML = "您好，尊敬的" + data.info.nickname

        }

    }
    //显示购物车商品数量
    async shopNum() {
        axios.defaults.headers.common['Authorization'] = localStorage.getItem("token")
        let res = await axios.get("http://localhost:8888/cart/list/?id=" + localStorage.getItem('user_id'))
        let { data, status } = res
        // console.log(data);
        let num = 0
        if (status == 200 && data.code == 1) {

            data.cart.map(v => {
                // console.log(v);
                return num += v.cart_number
            })

            this.$('.count').innerHTML = num
        }
    }
    //上一张
    preImg = (eve) => {
        this.numPhoto--
        if (this.numPhoto == -1) {
            this.numPhoto = 4
        }
        this.smallImg(this.numPhoto)

    }
    //下一张
    nextImg = () => {
        this.numPhoto++
        if (this.numPhoto == 5) {
            this.numPhoto = 0
        }

        this.smallImg(this.numPhoto)
    }
    //小图片的方法
    smallImg = (num) => {
        //取消 添加类名
        this.$('.list_item .current').className = ""
        this.$('.list_item li')[num].className = "current"
        //小照片  大照片的地址更改 
        let srcImg = this.$('.list_item li')[num].children[0].src
        // console.log(srcImg);
        this.$('.preview_img  .small').src = srcImg
        this.$('.preview_img  .bigimg').src = srcImg
    }
    numPhoto = 0
    //  切换图片
    changePhoto = (index, eve) => {
        this.numPhoto = index
        let tar = eve.target
        //取消 添加类名
        this.$('.list_item .current').className = ""
        this.$('.list_item li')[index].className = "current"
        //小照片  大照片的地址更改
        this.$('.preview_img  .small').src = tar.src
        this.$('.preview_img  .bigimg').src = tar.src

    }

    //获取小图片相对于文档的坐标
    boxL = this.$('.preview_img').offsetLeft;
    boxT = this.$('.preview_img').offsetTop;
    //小图片移动事件
    moveOut = (eve) => {
        // 小黄块的最大left和top值     
        let maxT = this.$('.preview_img').offsetHeight - this.$('.mask').offsetHeight;
        let maxL = this.$('.preview_img').offsetWidth - this.$('.mask').offsetWidth;
        // console.log(maxT, maxL);
        //  鼠标的相对于文档坐标
        let px = eve.pageX;
        let py = eve.pageY;
        // console.log(px, py);
        // 计算小黄块的左边
        let tmpX = px - this.boxL - this.$('.mask').offsetWidth / 2;
        let tmpY = py - this.boxT - this.$('.mask').offsetHeight / 2;


        if (tmpX < 0) tmpX = 0;
        if (tmpY < 0) tmpY = 0;
        // console.log(tmpY, maxT);
        // 右侧和下侧边界
        if (tmpX > maxL) tmpX = maxL;
        if (tmpY > maxT) tmpY = maxT;
        this.$('.mask').style.left = tmpX + 'px'
        this.$('.mask').style.top = tmpY + 'px'


        // 求出大图能够移动的最大位置

        let bImgPosL = this.$('.big').offsetWidth - this.$('.bigimg').offsetWidth;
        let bImgPosT = this.$('.big').offsetHeight - this.$('.bigimg').offsetHeight;
        // console.log(bImgPosL, bImgPosT);
        // 计算大图的实时位置
        // 小黄块实时位置/小黄块最大值==大图的实时位置/大图移动的最大距离
        let bImgTmpL = tmpX / maxL * bImgPosL;
        let bImgTmpT = tmpY / maxT * bImgPosT;
        //设置大图的位置
        this.$('.bigimg').style.left = bImgTmpL + 'px'
        this.$('.bigimg').style.top = bImgTmpT + 'px'



    }
    //小图片移入事件
    enterIn = () => {
        //遮罩  大图片显示
        this.$('.mask').style.display = "block"
        this.$('.big').style.display = "block"
    }
    //小图片移出事件
    enterOut = () => {
        //遮罩  大图片隐藏
        this.$('.mask').style.display = "none"
        this.$('.big').style.display = "none"
    }

    //切换  点击
    liClick(index) {
        //取消类名
        this.$('.detail_tab_list ul .current').className = ""
        this.$('.detail_tab_con .current').className = "item"
        //添加类名
        this.$('.detail_tab_list ul li')[index].className = "current"
        this.$('.detail_tab_con div')[index].className = "item current"


    }
    //获取节点
    $(ele) {
        let res = document.querySelectorAll(ele)
        return res.length == 1 ? res[0] : res
    }
}
new Detail()













//  https://ds.suning.com/ds/his/new/-yifu-0-1_0-autoComplateCallback_184b31b125a59d8c382d3d8382d23350.jsonp?callback=autoComplateCallback_184b31b125a59d8c382d3d8382d23350&_=1662864725374
 //https://ds.suning.com/ds/his/new/-${value}-0-1_0-autoComplateCallback_184b31b125a59d8c382d3d8382d23350.jsonp?callback=autoComplateCallback_184b31b125a59d8c382d3d8382d23350&_=1662864833533
